<?php
/**
 * --------------------------------------------------------------
 * 广告控制器
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\admin\model\Advert as AdvertModel;
use think\facade\Validate;

class Advert extends AdminBase
{
    /**
     * 广告列表
     */
    public function index()
    {
        $map  = $this->getSimpleSearchMap();
        $list = AdvertModel::where($map['where'])
                ->order('id desc')
                ->paginate(config('app.site_setting.list_rows'), false, [
                    'query' => $map['conditions']
                ]);

        $this->assign([
            'list'         => $list,
            'keyword'      => $map['conditions']['keyword'],
            'search_field' => $map['conditions']['search_field'],
            'title'        => '广告列表'
        ]);
        return $this->fetch();
    }
    
	/**
	 * 新增
	 */
	public function add()
	{
	    if ($this->request->isPost()) {
		    // 表单数据
            $data = $this->request->post();
            if (is_array($data['ad_time'])) {
                $data['start_time'] = isset($data['ad_time'][0]) ? $data['ad_time'][0] : '';
                $data['end_time']   = isset($data['ad_time'][1]) ? $data['ad_time'][1] : '';
            }

            // 验证
            $result = $this->validate($data, 'Advert');
            if (true !== $result) $this->error($result);
            if ($data['type'] != 0) {
                $data['link'] == '' && $this->error('链接不能为空');
                Validate::is($data['link'], 'url') === false && $this->error('链接不是有效的url地址'); // true
            }
			
			// 广告类型
            $tempContent = [];
            switch ($data['type']) {
                case 0: // 代码
                    $tempContent['code'] = $data['code'];
                    break;
                case 1: // 文字
                    $tempContent = [
                        'link'    => $data['link'],
                        'ad_text' => $data['ad_text'],
                        'color'   => $data['color'],
                    ];
                    break;
                case 2: // 图片
                    $tempContent = [
                        'link'    => $data['link'],
                        'one_pic' => $data['one_pic'],
                        'width'   => $data['width'],
                        'height'  => $data['height'],
                        'alt'     => $data['alt'],
                    ];
                    break;
                case 3: // flash
                    $tempContent = [
                        'link'    => $data['link'],
                        'width'   => $data['width'],
                        'height'  => $data['height'],
                    ];
                    break;
            }
            $data['content'] = json_encode($tempContent);
			
			unset($data['code']);
			unset($data['one_pic']);
			unset($data['ad_text']);
			unset($data['link']);
			unset($data['color']);
			unset($data['width']);
			unset($data['height']);
			unset($data['alt']);
            unset($data['ad_time']);
			
			if (AdvertModel::create($data)) {
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
		} else {
            $form_items = [
                ['type' => 'textarea', 'title' => 'JS代码', 'name' => 'code', 'remark' => '必填，支持html代码'],
                ['type' => 'image', 'title' => '单张图片', 'name' => 'one_pic', 'extra_class' => 'd-none', 'remark' => '必须'],
                ['type' => 'text', 'title' => '文字内容', 'name' => 'ad_text', 'extra_class' => 'd-none', 'remark' => '必填'],
                ['type' => 'text', 'title' => '链接地址', 'name' => 'link', 'extra_class' => 'd-none', 'remark' => '必填'],
                ['type' => 'colorpicker', 'title' => '文字颜色', 'name' => 'color', 'extra_class' => 'd-none', 'mode' => ''],
                ['type' => 'text', 'title' => '宽度', 'name' => 'width', 'extra_class' => 'd-none', 'remark' => '不用填写单位，只需填写具体数字'],
                ['type' => 'text', 'title' => '高度', 'name' => 'height', 'extra_class' => 'd-none', 'remark' => '不用填写单位，只需填写具体数字'],
                ['type' => 'text', 'title' => '图片描述', 'name' => 'alt', 'extra_class' => 'd-none', 'remark' => '即图片alt的值'],
            ];

            $this->assign([
                'form_items' => $form_items,
			    'title'      => '新增广告',
			]);
		    return $this->fetch();
		}
	}
	
	/**
	 * 编辑
	 */
	public function edit()
	{
		$id = input('id/d');
    	if ($id <= 0 || !is_numeric($id)) $this->error('参数错误');
	    if ($this->request->isPost()) {
		    // 表单数据
            $data = $this->request->post();
            if (is_array($data['ad_time'])) {
                $data['start_time'] = isset($data['ad_time'][0]) ? $data['ad_time'][0] : '';
                $data['end_time']   = isset($data['ad_time'][1]) ? $data['ad_time'][1] : '';
            }

            // 验证
            $result = $this->validate($data, 'Advert');
            if (true !== $result) $this->error($result);
            if ($data['type'] != 0) {
                $data['link'] == '' && $this->error('链接不能为空');
                Validate::is($data['link'], 'url') === false && $this->error('链接不是有效的url地址'); // true
            }
			
			// 广告类型
            $tempContent = [];
            switch ($data['type']) {
                case 0: // 代码
                    $tempContent['code'] = $data['code'];
                    break;
                case 1: // 文字
                    $tempContent = [
                        'link'    => $data['link'],
                        'ad_text' => $data['ad_text'],
                        'color'   => $data['color'],
                    ];
                    break;
                case 2: // 图片
                    $tempContent = [
                        'link'    => $data['link'],
                        'one_pic' => $data['one_pic'],
                        'width'   => $data['width'],
                        'height'  => $data['height'],
                        'alt'     => $data['alt'],
                    ];
                    break;
                case 3: // flash
                    $tempContent = [
                        'link'    => $data['link'],
                        'width'   => $data['width'],
                        'height'  => $data['height'],
                    ];
                    break;
            }
            $data['content'] = json_encode($tempContent);
			
			unset($data['code']);
			unset($data['one_pic']);
			unset($data['ad_text']);
			unset($data['link']);
			unset($data['color']);
			unset($data['width']);
			unset($data['height']);
			unset($data['alt']);
            unset($data['ad_time']);

            if (AdvertModel::update($data)) {
                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
		} else {
            $info = AdvertModel::get($id);
            
            $tempContent = json_decode($info['content'], true);
            
            $codeItem   = ['type' => 'textarea', 'title' => 'JS代码', 'name' => 'code', 'extra_class' => 'd-none', 'remark' => '必填，支持html代码'];
            $imgItem    = ['type' => 'image', 'title' => '单张图片', 'name' => 'one_pic', 'extra_class' => 'd-none', 'remark' => '必须'];
            $adTextItem = ['type' => 'text', 'title' => '文字内容', 'name' => 'ad_text', 'extra_class' => 'd-none', 'remark' => '必填'];
            $linkItem   = ['type' => 'text', 'title' => '链接地址', 'name' => 'link', 'extra_class' => 'd-none', 'remark' => '必填'];
            $colorItem  = ['type' => 'colorpicker', 'title' => '文字颜色', 'name' => 'color', 'extra_class' => 'd-none', 'mode' => ''];
            $widthItem  = ['type' => 'text', 'title' => '宽度', 'name' => 'width', 'extra_class' => 'd-none', 'remark' => '不用填写单位，只需填写具体数字'];
            $heightItem = ['type' => 'text', 'title' => '高度', 'name' => 'height', 'extra_class' => 'd-none', 'remark' => '不用填写单位，只需填写具体数字'];
            $altItem    = ['type' => 'text', 'title' => '图片描述', 'name' => 'alt', 'extra_class' => 'd-none', 'remark' => '即图片alt的值'];

            switch ($info['type']) {
                case 0: // 代码
                    $codeItem['value'] = $tempContent['code'];
                    unset($codeItem['extra_class']);
                    break;
                case 1: // 文字
                    $linkItem['value']   = $tempContent['link'];
                    $adTextItem['value'] = $tempContent['ad_text'];
                    $colorItem['value']  = $tempContent['color'];
                    unset($linkItem['extra_class']);
                    unset($adTextItem['extra_class']);
                    unset($colorItem['extra_class']);
                    break;
                case 2: // 图片
                    $imgItem['value']    = $tempContent['one_pic'];
                    $linkItem['value']   = $tempContent['link'];
                    $widthItem['value']  = $tempContent['width'];
                    $heightItem['value'] = $tempContent['height'];
                    $altItem['value']    = $tempContent['alt'];
                    unset($imgItem['extra_class']);
                    unset($linkItem['extra_class']);
                    unset($widthItem['extra_class']);
                    unset($heightItem['extra_class']);
                    unset($altItem['extra_class']);
                    break;
                case 3: // flash
                    $linkItem['value']   = $tempContent['link'];
                    $widthItem['value']  = $tempContent['width'];
                    $heightItem['value'] = $tempContent['height'];
                    unset($linkItem['extra_class']);
                    unset($widthItem['extra_class']);
                    unset($heightItem['extra_class']);
                    break;
            }

            $form_items = [
                $codeItem, $imgItem, $adTextItem, $linkItem, $colorItem, $widthItem, $heightItem, $altItem
            ];

            $this->assign([
                'form_items' => $form_items,
			    'title'      => '编辑广告',
				'info'       => $info
			]);
			
		    return $this->fetch();
		}
    }
    
	/**
	 * 删除
	 * @param integer $ids id值
	 */
	public function del($ids = 0)
	{
        (int) $ids || $this->error('参数错误');
        $map = ['id' => $ids];
		
        $result = AdvertModel::where($map)->delete();
        return $result ? $this->success('删除成功!') : $this->error('删除失败!');
	}
	
	/**
	 * 禁用/启用
	 * @param array $ids id数组
     * @param integer $status 状态值
     */
    public function setStatus($ids = [], $status)
    {
        empty($ids) && $this->error('请选择要操作的数据');
        !is_numeric((int) $status) && $this->error('参数错误');
        
        $map  = ['id' => $ids];
        $info = AdvertModel::where($map)->setField('status', $status);
        $tips = $status == 1 ? '启用' : '禁用';
        return $info !== FALSE ? $this->success($tips.'成功') : $this->error($tips.'失败');
    }
}